package com.ncloud.system.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.system.entity.Email;
import com.ncloud.system.mapper.EmailMapper;
import com.ncloud.system.service.MailService;

@Service
public class MailServiceImpl implements MailService{
	
	@Value("${mail.emailFrom}")  
    private String emailFrom;
	
    @Autowired
    private EmailMapper emailMapper;

    @Override
    public JSONObject insertEmail(Email email) {
        JSONObject result = new JSONObject();
        result.put("msgCode","1");
        result.put("msgDesc","成功");
        try {
            Email mail = validated(email);
            emailMapper.insertEmail(mail);
        } catch (Exception e) {
            result.put("msgCode","9");
            result.put("msgDesc","发送失败");
            e.printStackTrace();
            throw new UserException(e.getMessage());
        }
        return result;
    }


    private Email validated(Email email){
        if(StringUtils.isEmpty(email)){
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"发送邮件参数信息为空，请检查！");
        }
        //Email email = JSON.parseObject(param.toJSONString(),Email.class);
        if(StringUtils.isEmpty(email.getSysCode())){
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"系统编码未设置：sysCode");
        }
        if(StringUtils.isEmpty(email.getSubject())){
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"邮件主题未设置：subject");
        }
        if(StringUtils.isEmpty(email.getMsgFrom())){
            email.setMsgFrom(emailFrom);
        }
        if(StringUtils.isEmpty(email.getMsgTo())){
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"接收邮件人未设置：msgTo");
        }
        if(StringUtils.isEmpty(email.getContent())){
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"邮件内容未设置：content");
        }

        if(StringUtils.isEmpty(email.getMsgType())){
            email.setMsgType("0");
        }else if("1".equals(email.getMsgType())){
            if(StringUtils.isEmpty(email.getTemplateName())){
                throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"请检查模板名称设置：templateName");
            }
        }

        //设置默认初始状态
        if(StringUtils.isEmpty(email.getMsgCode())){
            email.setMsgCode("0");
        }
        email.setMsgResult("入表成功");
        return email;
    }
}
